package com.yifi.system.controller;

import java.util.Date;

import cn.hutool.crypto.symmetric.AES;
import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.yifi.common.DBHelper;
import com.yifi.common.base.InitController;
import com.yifi.common.constant.ConstantInit;
import com.yifi.common.model.AjaxResult;
import com.yifi.common.utils.DataBase;
import com.yifi.common.utils.DateUtils;
import com.yifi.common.utils.StringUtils;
import com.yifi.common.utils.ToolDataBase;
import com.yifi.common.wx.WeixinUtil;
import com.yifi.common.wx.WxSendMsg;
import com.yifi.system.domain.MisUser;
import com.yifi.system.service.MisUserService;
import com.yifi.system.service.OrgInfoService;
import com.yifi.system.service.OrgInfoService.ReturnOrg;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;

@Path(value = "/", viewPath = "/")
public class LoginController extends InitController {

	@Inject
	MisUserService misUserService;

	public void index() {
		DataBase db = ToolDataBase.getDbInfo();
		setAttr("captcha", db.captchaEnabled);
		setAttr("captchaType", db.captchaType);

		// 判断是否是内网登录
		String serverip = getRequest().getServerName();
		if (serverip.contains("localhost") || serverip.contains("192.168.") || serverip.contains("127.0.0.1")) {
			setAttr("isnet", false);
		} else {
			setAttr("isnet", true);
		}
		// setAttr("isnet", false);

		boolean isclose = false;
		String errorMsg = "";
		String sql = "select * from sys_option where out_flag='1' "; // 查询验证时间戳
		Record record = Db.findFirst(sql);
		if (record != null) {
			Date date = record.getDate("out_time");
			Date now = DateUtils.getNowDate();
			long day = DateUtil.between(now, date, DateUnit.DAY, false);
			if (day > 0 && day <= 30) // 提示
			{
				errorMsg = "系统使用受限，请有关部门抓紧办理后续手续，以免影响正常使用！<br/>系统还有<span style='color:red;font-weight:bold;font-size:2em'>"
						+ day + "</span>天，将自动关闭";
			} else if (day <= 0) // 禁止
			{
				isclose = true;
				errorMsg = "试用期已到";
			}
		} else // 不处理
		{
			errorMsg = "";
		}

		setAttr("isclose", isclose);
		setAttr("errorMsg", errorMsg);

		render("login.html");
	}

	public void getCaptcha() {
		renderCaptcha();
	}

	@Inject
	private OrgInfoService orgInfoService;

	public void send() {
		String username = getPara("username", "").toLowerCase();
		String password = getPara("password", "").toLowerCase();
		String rememberme = getPara("rememberme", "");
		// 随机生成密钥  SymmetricAlgorithm.AES.getValue()
		String key="0123456789ABHAEQ";
		String vi="adlotsoft_123456";   //16位
		// 构建
		AES aes = new AES("CBC", "PKCS7Padding",
				// 密钥，可以自定义
				key.getBytes(),
				// iv加盐，按照实际需求添加
				vi.getBytes());
		// 前端传递的 AES加密的数据解码
		username = aes.decryptStr(username);
		password = aes.decryptStr(password);

		String mac = getPara("mac", "");

		DataBase db = ToolDataBase.getDbInfo();
		if (db.captchaEnabled) {
			if (!validateCaptcha("validateCode")) {
				renderJson(error("验证码错误！"));
				return;
			}
		}

		AjaxResult result;

		MisUserService misUserService = new MisUserService();
		String sql = "select t1.*,(select cname from mis_org where ccode=t1.cdept) as orgname"
				+ ",(select db_type from org_info where ccode=t1.c_pro) as db_type"
				+ ",(select ccode_auto from org_info where ccode=t1.c_pro) as ccode_auto "
				+ " from mis_user t1 where user_num=? and cpass=?";
		MisUser misUser = (MisUser) misUserService.getDao().findFirst(sql, username, password);
		if (misUser != null) {
			String c_pro = misUser.getC_pro();
			if (StrUtil.isNotEmpty(c_pro)) {
				ReturnOrg ro = orgInfoService.checkOrg(c_pro);
				if (ro.getCode() == -1) {
					result = error(ro.getMsg());
				} else if (ro.getCode() == 0) {
					result = error(ro.getMsg());
				} else {
					misUserService.setSession(this, misUser, false);
					setSessionAttr("mac", mac);// 用户登录名
					result = success("登录成功！");
				}
			} else {
				misUserService.setSession(this, misUser, false);
				setSessionAttr("mac", mac);// 用户登录名
				result = success("登录成功！");
			}
		} else {
			result = error("用户名或者密码出错！");
		}
		renderJson(result);
	}

	public void logout() {

		removeSessionAttr(ConstantInit.loginUser);
		redirect("/");

	}

	// 生成验证码
	public void Vaild() {
		AjaxResult strres = null;
		String username = getPara("username", "").toLowerCase();
		String password = getPara("password", "").toLowerCase();
		String sql = "";
		sql = "select t1.* from mis_user t1 where st_flag='1' and MD5(user_num)=?";
		Record ruser = Db.findFirst(sql, username);
		if (password.equals(ruser.get("cpass"))) {
			String ccode = ruser.getStr("ccode");
			Date redate = ruser.getDate("wx_date");

			Date nodate = DBHelper.GetDateNow();
			String wx_code = RandomUtil.randomString(6);
			ruser.set("wx_code", wx_code);
			ruser.set("wx_date", nodate);
			Db.update("mis_user", "ccode", ruser);
			String wx_userid = ruser.getStr("wx_userid");

			sql = "select cvalue from sys_option where ccode='CorpID'";
			String corpId = DBHelper.GetString(sql);
			sql = "select cvalue from sys_option where ccode='Secret'";
			String secret = DBHelper.GetString(sql);
			sql = "select cvalue from sys_option where ccode='AgentId'";
			String agentid = DBHelper.GetString(sql);

			// String access_token = WeixinUtil.getAccessToken(ParamesAPI.corpId,
			// ParamesAPI.secret).getToken();
			String access_token = WeixinUtil.getAccessToken(corpId, secret).getToken();
			// String AgentId="1000002";
			if (StringUtils.isNotEmpty(wx_userid)) {
				// Post的数据
				String PostData = WxSendMsg.STextMsg(wx_userid, "@all", "@all", agentid, wx_code);
				int result = WeixinUtil.PostMessage(access_token, "POST", PostData);

				// 打印结果
				if (0 == result) {
					System.out.println("操作成功");
					strres = success("操作成功");
				} else {
					System.out.println("操作失败");
					strres = error("操作失败");
					setAttr("errorMsg", "当前用户未微信注册！");
					redirect("");
				}

			} else {
				strres = error("微信未注册到系统中，操作失败");
			}
		} else {
			strres = success("操作失败");
		}

		renderJson(strres);
	}

	// 验证登录
	public void VaildCode() {
		AjaxResult strres = null;
		String username = getPara("username", "").toLowerCase();
		String password = getPara("password", "").toLowerCase();
		boolean isnet = getParaToBoolean("isnet", false);

		String sql = "";
		sql = "select t1.* from mis_user t1 where st_flag='1' and MD5(user_num)=?";
		MisUser ruser = MisUser.dao.findFirst(sql, username);

		if (isnet) {
			String wx_code = getPara("wx_code", "");
			wx_code = wx_code.toUpperCase();

			if (password.equals(ruser.get("cpass")) && wx_code.equals(ruser.get("wx_code"))) {
				misUserService.setSession(this, ruser, false);

				strres = success("成功！");
			} else {
				strres = error("验证码错误！");
			}
		} else {
			if (password.equals(ruser.get("cpass"))) {
				misUserService.setSession(this, ruser, false);

				strres = success("成功！");
			} else {
				strres = error("登录失败！");
			}
		}
		renderJson(strres);
	}

}
